<template>
  <div class="setting-content inside-comment">
    <h2 class="setting-header">
      <strong>留言数据</strong>
    </h2>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane :label="`待回复(${replayStateData.awaitReplyCount})`" name="awaitReplyCount"></el-tab-pane>
      <el-tab-pane :label="`审核退回(${replayStateData.refuseCount})`" name="refuseCount"></el-tab-pane>
    </el-tabs>
    <div class="header-top">
      <SearchCmp v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="searchForm" style="margin: 10px 0" @onSubmit="handleGetFormManageList" />
      <!-- <div class="left-box">
        
        <div class="state">
          <span>回复状态：</span>
          <el-select
            v-model="searchForm.isReply"
            style="width: 100px"
            @change="handleReplyChange"
          >
            <el-option
              v-for="item in replyStatusOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="state">
          <span>公开状态：</span>
          <el-select
            v-model="searchForm.isOpen"
            style="width: 100px"
            @change="handleOpenChange"
          >
            <el-option
              v-for="item in isOpenStatusOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="state">
          <span>审核状态：</span>
          <el-select
            v-model="searchForm.state"
            style="width: 100px"
            @change="handleOpenChange"
          >
            <el-option
              v-for="item in auditStateOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="state">
          <span>排序：</span>
          <el-select
            v-model="searchForm.sort"
            style="width: 100px"
            @change="handleSortChange"
          >
            <el-option
              v-for="item in sortOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="search">
            <el-input
              placeholder="输入用户名或留言内容关键词"
              @keydown.enter="handleGetFormManageList"
              v-model="searchForm.keyword"
            >
              <template #suffix>
                <i class="iconfont" @click="handleGetFormManageList">&#xe643;</i>
              </template>
            </el-input>
        </div>


      </div> -->
      
      <!-- <div class="right-num">
        <p @click="handleGetNotReplay">待回复：<span >{{replayStateData.awaitReplyCount}}</span></p>
        <p @click="handleGetFail">审核退回：<span >{{replayStateData.refuseCount}}</span></p>
      </div> -->
    </div>
    <RuifoxTable
      :loading="tableLoading"
      :table-data="tableData"
      :field-list="fieldList"
      :default-index="true"
      :default-checkbox="true"
    >

      <template #default-checkbox="{ element }">
        <div class="table-div-check">
          <el-checkbox
            class="unmover"
            v-model="element.checked"
            @change="handleCheckTable(element.id)"
            size=""
          />
        </div>
      </template>

      <!-- 设置热门 -->
      <template #isTop='{element}'>
        <div class="table-td-top">
          <span v-permission="['content:manage:top']" :class="{'ding-yes': element.isTop,'ding-no': !element.isTop}" @click="handleTop(element)">热</span>
        </div>
      </template>

      <!-- 内容列 -->
      <template #content="{ element }">
        <div class="content-container">
          <i class="is-read" v-if="element.isRead == false"></i>
          <span class="content-text" @click="showDetail(element)">{{element.content.content[0].value}}</span>
        </div>
      </template>

      <!-- 创建时间列 -->
      <template #publishTime="{ element }">
        {{ dayjs(element.publishTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>

      <!-- 所属分类 -->
      <template #typeName="{ element }">
        <span v-if="!element.typeName" style="color: #444;margin-left: 5px;">—</span>
      </template>

      <!-- 回复状态列 -->
      <template #isReply="{ element }" >
        <el-tag v-if="element.isReply" type="success">已回复</el-tag>
        <el-tag v-else type="warning">待回复</el-tag>
      </template>

      <!-- 审核状态列 -->
      <template #state="{ element }">
        <div >
          <el-tag v-if="element.state == 3" type="warning">待审核</el-tag>
          <el-tag v-if="element.state == 1" type="success">审核通过</el-tag>
          <el-tag v-if="element.state == 0" type="danger">审核失败</el-tag>
          <span v-if="element.state == 99" style="color: #444;margin-left: 5px;">—</span>
        </div>
      </template>

      <!-- 公开状态列 -->
      <template #isOpen="{ element }" >
        <el-switch
          v-model="element.isOpen"
          :active-value="1"
          :inactive-value="0"
          :before-change="() => handleOpen(element)"
        />
      </template>

      <!-- 回复时间列 -->
      <template #replyTime="{ element }">
        {{ dayjs(element.replyTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>

      <!-- 操作列 -->
      <template #options="{ element }">
        <div class="table-td-option unmover">
          <el-button
            type="primary"
            size="small"
            link
            @click="showDetail(element)"
            >回复</el-button
          >
          <!-- <el-button
            v-if="element.isDeleted == 0"
            type="primary"
            size="small"
            link
            @click="handleEdit(element)"
            >编辑</el-button
          > -->
          <el-button
            type="primary"
            size="small"
            link
            @click="handleDelete(element)"
            >删除</el-button
          >
        </div>
      </template>
    </RuifoxTable>
    <PaginationView
      :total="queryData.total"
      :pageSize="queryData.pageSize"
      :currentPage="queryData.currentPage"
      :allChoose="isAllChooseBtn"
      :pageChoose="isPageChooseBtn"
      :options="batchOptions"
      :checkedNum="checkedNum"
      :canChoose="queryData.total > 0"
      @changeSize="handleSizeChange"
      @currentChange="handleCurrentChange"
      @changePageChoose="handlePageChoose"
      @changeAllChoose="handleAllChoose"
      @invertChoose="handleInvertChoose"
      @checkOption="handleBatchOptions"
      @refreshList="handleGetFormManageList"
      @cancelChoose="handleResetPagination"
    />

    <!-- 回复 -->
    <el-dialog v-model="replyDialogVisible" title="回复留言" width="1000px">
      <TinymceEditor
        v-model:modelValue="replyForm.content.content"
        :minHeight="500"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleReplySubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog v-model="editDialogVisible" title="修改留言" width="1000px">
      <TinymceEditor
        v-model:modelValue="editForm.content"
        :minHeight="500"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="留言详情"
      width="1000px"
      class="comment-detail-dialog"
    >
      <el-scrollbar height="600px">
        <div class="comment-detail">
          <!-- 留言主体 -->
          <!-- <div class="comment-header">
            <div class="header-title">
              <span class="title">网友留言</span>
            </div>
          </div> -->
          <div class="main-comment">
            <!-- 留言标题栏 -->
            <div class="comment-title">
              <div class="left">
                <span class="label">留言人：</span>
                <span class="value">{{ currentDetail.userName }}</span>
              </div>
              <div class="right">
                <el-tag
                  :type="currentDetail.isOpen ? 'success' : 'warning'"
                  size="small"
                >
                  {{ currentDetail.isOpen ? "已公开" : "未公开" }}
                </el-tag>
                <el-tag
                  type="warning"
                  size="small"
                  v-if="currentDetail.isMute"
                >
                  已标记
                </el-tag>
                <div class="button-list" v-if="userReplay">
                <!-- <div class="button-list" > -->
                  <el-button
                    type="primary"
                    link
                    @click="handleReply(currentDetail)"
                    v-if="!currentDetail.isMute"
                    >回复</el-button
                  >
                  <el-button
                    type="primary"
                    link
                    @click="cancelmark(currentDetail)"
                    v-if="currentDetail.isMute"
                    >取消标记</el-button
                  >
                  <el-button
                    type="primary"
                    link
                    @click="handlemark(currentDetail)"
                    v-else
                    >标记</el-button
                  >
                  <el-button
                    v-if="!(currentDetail.children && currentDetail.children.length > 0) && !currentDetail.isMute"
                    type="primary"
                    link
                    @click="movemark(currentDetail)"
                    >移动</el-button
                  >
                  <el-button
                    type="primary"
                    link
                    v-if="!currentDetail.isMute"
                    @click="copymark(currentDetail)"
                    >推送</el-button
                  >
                </div>
              </div>
            </div>
            <!-- 留言信息 -->
            <div class="comment-info">
              <div class="info-item">
                <span class="label">IP地址：</span>
                <span class="value">{{ currentDetail.ip }}</span>
              </div>
              <div class="info-item">
                <span class="label">留言时间：</span>
                <span class="value">{{
                  dayjs(currentDetail.publishTime).format("YYYY-MM-DD HH:mm:ss")
                }}</span>
              </div>
              <div class="info-item">
                <span class="label">所属留言表：</span>
                <span class="value">{{ currentDetail.formName }}</span>
              </div>
              <div class="info-item">
                <span class="label">所属分类：</span>
                <span class="value">{{ currentDetail.typeName }}</span>
              </div>
              <div class="info-item">
                <span class="label">留言内容：</span>
              </div>
            </div>
            <!-- 分割线 -->
            <el-divider style="margin-bottom: 15px;"/>
            <!-- 留言内容 -->
            <FormRenderer
              :fields="currentDetail.content.content"
              :model-value="{}"
              disabled
              label-width="100px"
            />
            <!-- <div
              class="comment-content"
              v-html="currentDetail.content.content"
            ></div> -->
          </div>

          <!-- 回复列表 -->
          <div v-if="currentDetail?.children?.length" class="reply-list">
            <div class="reply-header">
              <div class="header-title">
                <span class="title">回复</span>
                <span class="count"
                  >(共 {{ currentDetail.children?.length }} 条)</span
                >
              </div>
            </div>
            <div class="reply-items">
              <div
                v-for="reply in currentDetail.children"
                :key="reply.id"
                class="reply-item"
              >
                <div class="reply-info">
                  <div class="left">
                    <span class="username">回复人：{{ reply.userName }}</span>
                    <span class="time"
                      >回复时间：{{
                        dayjs(reply.publishTime).format("YYYY-MM-DD HH:mm:ss")
                      }}</span
                    >
                  </div> 
                  <div class="right">
                    <div class="reply-actions">
                      <el-tag v-if="reply.state == 3" type="warning">待审核</el-tag>
                      <el-tag v-if="reply.state == 1" type="success">审核通过</el-tag>
                      <el-tag v-if="reply.state == 0" type="danger">审核失败</el-tag>
                      <el-button v-permission="['flow:task:cc:process']" type="primary" size="small" link @click="handleAuditProgress(reply.processInstanceId)">{{reply.state == 0 ? '审核意见' :'审核进度'}}</el-button>
                    </div>
                  </div>
                </div>
                <el-divider />
                <div
                  class="reply-content"
                  v-html="reply.content?.content"
                ></div>
                <el-divider />
                <div class="audit-progress" style="display: none;">
                  <div class="audit-title">审核进度</div>
                  <div class="audit-list">
                    <div class="audit-item">
                      <el-icon color="#67c23a"><SuccessFilled /></el-icon>
                      <p class="username">审核人1：<el-tag type="success">审核通过</el-tag></p>
                      <p class="time">时间：{{ dayjs(reply.publishTime).format("YYYY-MM-DD HH:mm:ss") }}</p>
                    </div>
                    <div class="audit-item">
                      <el-icon color="#bd3124"><CircleCloseFilled /></el-icon>
                      <p class="username">审核人2：<el-tag type="danger">审核退回</el-tag>
                        <el-popover
                          placement="top-start"
                          title="退稿原因："
                          :width="200"
                          trigger="hover"
                          content="暂无退稿意见"
                        >
                          <template #reference>
                            <el-icon color="#ff9700"><QuestionFilled /></el-icon>
                          </template>
                        </el-popover>
                      </p>
                      <p class="time">时间：{{ dayjs(reply.publishTime).format("YYYY-MM-DD HH:mm:ss") }}</p>
                    </div>
                    <div class="audit-item">
                      <el-icon color="#9a9a9a"><RemoveFilled /></el-icon>
                      <p class="username">审核人1：<el-tag type="warning">待审核</el-tag></p>
                      <p class="time">时间：{{ dayjs(reply.publishTime).format("YYYY-MM-DD HH:mm:ss") }}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无回复" />
        </div>
      </el-scrollbar>
    </el-dialog>
    <!-- 审核进度  -->
    <el-dialog
      v-model="showAuditProgress"
      title="审核进度"
      width="600px"
      class="process-dialog"
    >
      <AuditProgress v-if="showAuditProgress" :id="processInstanceId" />
    </el-dialog>
    <!-- 移动-推送留言 选择留言表 -->
    <el-dialog v-model="showAllForm" :title="isMoveComment ? '移动留言' : '推送留言'" width="500px">
      <el-form :model="changeForm" label-width="80px">
        <el-form-item label="留言表" prop="pid" >
          <el-select v-model="changeComment.formId" placeholder="选择留言表">
            <el-option
              v-for="item in formList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              @click="handleFormChange(item)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="留言分类" prop="pid">
          <el-select v-model="changeComment.typeId" placeholder="选择留言分类">
            <el-option
              v-for="item in classifyFlow"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAllForm = false">取消</el-button>
          <el-button type="primary" @click="saveChangeComment">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, onBeforeMount } from "vue";
import {
  getCommentsByPageMessages,
  deleteCommentMessages,
  batchDeleteCommentMessages,
  insertByBackGroundCommentMessages,
  updateComment,
  isOpeCommentMessages,
  batchIsOpenedCommentMessages,
  getCommentByIdCommentMessages,
  getCommentTreeByIdCommentMessages,
  canReplyCommentMessages,
  setTopCommentMessages,
  markedManagerMarkedUser,
  batchRecommendCommentMessages,
  selectAwaitAndRefuseCommentMessages,
  blockedManagerMarkedUser,
  moveCommentMessages,
  copyCommentMessages,
  readCommentMessages
} from "@/api/comment";
import { selectfunction } from "@/api/setting"; 
import { selectListCommentForm } from "@/api/form"; 
import { 
  cancelMarkedManagerMarkedUser,
  selectByMarkedManagerMarkedUser,
 } from "@/api/user";
import TinymceEditor from "@/components/TinymceEditor.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { SuccessFilled, CircleCloseFilled, QuestionFilled, RemoveFilled } from '@element-plus/icons-vue'
import { tableList as mixTable } from "@ruifox-cms/utils";
import dayjs from "dayjs";
import AuditProgress from "../components/AuditProgress";
import FormRenderer from "../components/FormRenderer";
import { useStore } from 'vuex'

//获取当前用户信息
const store = useStore(); 
const userInfo = ref();
userInfo.value = store.state.base.userInfo

// 表格显示字段
const fieldList = ref([
  {
    title: "热门",
    name: "isTop",
    width: 40,
    hideTitle: true,
  },
  // {
  //   title: "推荐",
  //   name: "recommend",
  //   width: 40,
  //   hideTitle: true,
  // },
  {
    title: "留言标题（点击查看详情）",
    name: "content",
    width: 250,
  },
  {
    title: "留言人",
    name: "userName",
  },
  {
    title: "留言ip",
    name: "ip",
  },
  {
    title: "留言时间",
    name: "publishTime",
  },
  {
    title: "所属留言",
    name: "formName",
  },
  {
    title: "所属分类",
    name: "typeName",
  },
  {
    title: "回复状态",
    name: "isReply",
    visible: true
  },
  {
    title: "审核状态",
    name: "state",
    visible: true
  },
  {
    title: "是否公开",
    name: "isOpen",
    visible: true
  },
  
  // {
  //   title: "回复人",
  //   name: "username",
  // },
//   {
//     title: "回复数量",
//     name: "number",
//   },
//   {
//     title: "回复时间",
//     name: "replyTime",
//   },
  {
    title: "操作",
    name: "options",
    width: 150,
    fixed: "right",
  },
]);

const props = defineProps({
  defaultQuery: {
    type: Object,
    default: () => {
      return {
        keyword: "", //关键词
        state: "", //状态 99默认 3待审核，1审核通过，0审核不退回
        sort: "", //排序
        isReply: "", //回复状态
        isOpen: "", //公开状态
        currentPage: 1,
        pageSize: 10,
        total: "",
        isDeleted: 0,
      };
    },
  },
});

//搜索
const searchForm = ref(JSON.parse(JSON.stringify(props.defaultQuery)));

//状态
const sortOption = ref([
  { label: "发布时间降序", value: 0 },
  { label: "发布时间升序", value: 1 },
]);

const replyStatusOption = ref([
  { label: "待回复", value: 0 },
  { label: "已回复", value: 1 },
]);

const isOpenStatusOption = ref([
  { label: "隐藏", value: 0 },
  { label: "公开", value: 1 },
]);

const isHotStatusOption = ref([
  { label: "普通", value: 0 },
  { label: "热门", value: 1 },
]);

const auditStateOption = ref([
  { label: "默认", value: 99 },
  { label: "待审核", value: 3 },
  { label: "审核通过", value: 1 },
  { label: "审核退回", value: 0 },
]);

// 用户列表可搜索字段
const searchCmpArray = ref([
  { label: '回复状态', key: 'isReply', form_type: 'select', options: replyStatusOption.value },
  { label: '公开状态', key: 'isOpen', form_type: 'select', options: isOpenStatusOption.value },
  { label: '审核状态', key: 'state', form_type: 'select', options: auditStateOption.value },
  { label: '排序', key: 'sort', form_type: 'select', options: sortOption.value },
  { label: '热门', key: 'isTop', form_type: 'select', options: isHotStatusOption.value },
  { label: '搜索', key: 'keyword'}
])

const {
  queryData,
  tableData: oriTableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  checkedList,
  isAllSearch,
  getTableData,
  //   handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination,
} = mixTable({
  getListApi: getCommentsByPageMessages,
  batchFuncApi: batchDeleteCommentMessages,
});

const defaultQuery = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  isDeleted: 0,
  state: "",
  isReply: "",
});

Object.assign(queryData, defaultQuery);
const tableData = ref([]);

// 获取列表
const handleGetFormManageList = async () => {
  // searchForm.value.userId = userInfo.value.id
  // queryData.userId = userInfo.value.id
  try {
    let res = await getCommentsByPageMessages(searchForm.value);
    refreshTableData(res.data);
    await getReplayStateData()
  } catch (error) {
    ElMessage.error("获取数据失败");
  }
};
//初始化表格数据
const initTableData = async () => {
  searchForm.value = JSON.parse(JSON.stringify(props.defaultQuery));
  await handleGetFormManageList();
}
initTableData();

//新留言和审核退回数据
const replayStateData = reactive({
  awaitReplyCount: 0,
  refuseCount: 0,
});
const activeName = ref('all')
const handleClick = (tab) => {
  let name = tab.props.name;
  if (name === "awaitReplyCount") {
    searchForm.value = JSON.parse(JSON.stringify(props.defaultQuery))
    searchForm.value.isReply = 0;
    Object.assign(queryData, defaultQuery);
    queryData.isReply = 0;
    handleGetFormManageList();
  } else if (name === "refuseCount") {
    searchForm.value = JSON.parse(JSON.stringify(props.defaultQuery))
    searchForm.value.state = 0;
    Object.assign(queryData, defaultQuery);
    queryData.state = 0;
    handleGetFormManageList();
  } else if (name === "all") {
    searchForm.value = JSON.parse(JSON.stringify(props.defaultQuery))
    Object.assign(queryData, defaultQuery);
    handleGetFormManageList();
  }
}
  
//获取留言设置
const commentSetting = ref()
const getCommentSetting = async () => {
  const res = await selectfunction()
  commentSetting.value = res.data 
}
getCommentSetting()

const getReplayStateData = async () => {
  let replayRes = await selectAwaitAndRefuseCommentMessages();
  replayStateData.awaitReplyCount = replayRes.data.awaitReplyCount;
  replayStateData.refuseCount = replayRes.data.refuseCount;
}

getReplayStateData()
//更新分页器
const refreshPage = (data) => {
  queryData.total = data.total;
  queryData.pageSize = data.pageSize;
  queryData.currentPage = data.currentPage;
}
//更新表格数据
const refreshTableData = (data) => {
  oriTableData.value = data.list;
  searchForm.value.total = data.total;
  refreshPage(data)
  watch(oriTableData, () => {
    // tableData.value = oriTableData.value
    tableData.value = oriTableData.value.map((comment) => {
    //   const tempElement = document.createElement("div");
    //   tempElement.innerHTML = comment.value || "";
    //   comment.value = tempElement.textContent || tempElement.innerText;
    //   comment.value = comment.value.replace(/\s+/g, "");
      return comment;
    });
  });
}

// 置顶 取消置顶
const handleTop = data => {
  const obj = {
    commentId: data.id,
    isTop: data.isTop ? 0 : 1
  }
  setTopCommentMessages(obj).then(res => {
    if (res.code === 20000) {
      ElMessage({
        showClose: true,
        message: data.isTop ? '取消热门成功' : '设置热门成功',
        type: 'success'
      })
    }
    handleGetFormManageList()
    // getTableData()
  })
}
// 批量置顶

//批量推荐
const batchRecommend = async () => {
  // console.log("checkedList.value",checkedList.value);
  
  let idlist = []
  idlist = checkedList.value
  const data = {
    ids: idlist,
    isTop: 1,
  };
  console.log("data",data);
  
  batchRecommendCommentMessages(data).then((res) => {
    if (res.code === 20000) {
      ElMessage.success("状态更新成功");
      handleGetFormManageList();
      isAllSearch.value = false;
      isAllChooseBtn.value = false;
      checkedList.value = [];
    }
  });
}
// 批量操作
const batchOptions = ref([
  { name: "删除", value: "delete", icon: "&#xe74b;" },
  { name: "公开", value: "open", icon: "&#xeb46;" },
  { name: "热门", value: "recommend", icon: "&#xe6f4;" },
]);
const handleBatchOptions = (data) => {
  if (data === "delete") {
    handleBatchDelete();
  } else if (data === "open") {
    handleBatchOpen();
  } else if (data === "recommend") {
    batchRecommend();
  }
};

// 回复相关
const replyDialogVisible = ref(false);
const replyForm = ref({
  catId: 0,
  content: {
    content: "",
  }, 
  formId: 0,
  image: "",
  pid: null,
  privacy:true,
  title: "",
  // userId: "",
  userName: "",
  video: ""
});

// 处理回复按钮点击
const handleReply = (element) => {
  console.log("element",element);
  replyForm.value.pid = element.id;
  replyForm.value.content.content = "";
  replyForm.value.formId = element.formId;
  replyForm.value.catId = element.catId;
  replyDialogVisible.value = true;
};

//处理标记按钮
const handlemark = (element) => {
  let theInputValue = ''
  ElMessageBox.prompt('是否标记该留言，将隐藏改留言并且标记用户？', '标记确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入标记原因',
    inputValue: theInputValue,
  }).then(async ({value}) => {
    if(!value.trim()){
      ElMessage.error('请输入标记原因')
      return
    }
    await isOpeCommentMessages({
      id: element.id,
      isOpen: 0,
    })
    theInputValue = value;
    let res = await markedManagerMarkedUser({
      commentId: element.id,  
      ip: element.ip,
      userId: element.userId,
      userName: element.userName,
      content: theInputValue
    })
    if (res.code === 20000) {
      ElMessage.success("已标记该留言");
    
      refreshDetailData();
      handleGetFormManageList()
    }

    const markRes = await selectByMarkedManagerMarkedUser({ userId: element.userId });
    if (markRes.data.length >= commentSetting.value.muteLimit) {
      ElMessage.warning("用户被标记次数过多，已禁言");
    } else if (markRes.data.length >= commentSetting.value.blockLimit) {
      const blockRes = await blockedManagerMarkedUser()
      if(blockRes.code === 20000){
        ElMessage.warning("用户被标记次数过多，已拉黑");
      }
    }
  })
};
//取消标记
const cancelmark = async (element) => {
  console.log("element",element);
  const res = await cancelMarkedManagerMarkedUser({
    commentId: element.id,
    userId: element.userId
  })
  if (res.code == 20000) {
    ElMessage.success("取消标记成功");
    refreshDetailData();
    handleGetFormManageList()
  }
}
//获取留言表单
const showAllForm = ref(false);
const formList = ref([])
const classifyFlow = ref("")
const getForm = async () => {
  // const res = await selectListCommentForm({currentPage:1,pageSize:100,isEnabled:true});
  const res = await selectListCommentForm({currentPage:1,pageSize:10,isEnabled: 1});
  if (res.code === 20000) {
    formList.value = res.data.list
    console.log("formList.value",formList.value);
    
  }
}
const handleFormChange = (item) => {
  classifyFlow.value = ""
  changeComment.value.typeId = ""
  if (item.classifyFlow.length > 1) {
    classifyFlow.value = item.classifyFlow
  }
}

//处理移动留言
const changeComment = ref({
  commentId:"",
  formId:"", 
  typeId:""
})
const isMoveComment = ref(false)
const movemark = (element) => {
  showAllForm.value = true
  isMoveComment.value = true
  changeComment.value.commentId = element.id
};
const copymark = (element) => {
  showAllForm.value = true
  isMoveComment.value = false
  changeComment.value.commentId = element.id
};
//提交移动-推送
const saveChangeComment = async () => {
  //检查更改后的留言是否 必填项都填了
  if(changeComment.value.formId == "") {
    ElMessage.warning('请选择留言表单')
    return
  } else if(classifyFlow.value != "") {
    if(changeComment.value.typeId == "") {
      ElMessage.warning('请选择留言表单分类')
      return
    }
  }
  if(isMoveComment.value == true) {
    const res = await moveCommentMessages(changeComment.value)
    if(res.code == 20000) {
      ElMessage.success('移动成功')
    }
  } else {
    const res = await copyCommentMessages(changeComment.value)
    if(res.code == 20000) {
      ElMessage.success('推送成功')
    }
  }
  showAllForm.value = false
  detailDialogVisible.value = false
  handleGetFormManageList()
}
// 修改回复提交处理函数
const handleReplySubmit = async () => {
  if (!replyForm.value.content.content.trim()) {
    ElMessage.warning("请输入回复内容");
    return;
  }

  try {
    await insertByBackGroundCommentMessages(replyForm.value);
    ElMessage.success("回复成功");
    replyDialogVisible.value = false;
    await getTableData();
    // 如果详情弹窗打开，重新获取详情数据
    if (detailDialogVisible.value) {
      await refreshDetailData();
    }
  } catch (error) {
    ElMessage.error("回复失败");
  }
};

// 修改
const editDialogVisible = ref(false);
const editForm = ref({});

// const handleEdit = async (data) => {

//     editForm.value = {
//         id: data.id,
//         content: data.content,
//     };
//     editDialogVisible.value = true;
   
// };

const handleEditSubmit = async () => {
  if (!editForm.value.content.trim()) {
    ElMessage.warning("请输入留言内容");
    return;
  }

  try {
    await updateComment(editForm.value);
    ElMessage.success("修改成功");
    editDialogVisible.value = false;
    await getTableData();
    // 如果详情弹窗打开，重新获取详情数据
    if (detailDialogVisible.value) {
      await refreshDetailData();
    }
  } catch (error) {
    ElMessage.error("修改失败");
  }
};

// 删除
const handleDelete = async (data) => {
  ElMessageBox.confirm("是否删除该留言？", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await deleteCommentMessages({ id: data.id });
    if (res.code === 20000) {
      ElMessage.success("删除成功");
      handleGetFormManageList()
      // 如果删除的是当前详情中的评论，关闭详情弹窗
      if (detailDialogVisible.value && currentDetail.value.id === data.id) {
        detailDialogVisible.value = false;
      }
      // 如果删除的是详情中的回复，更新详情数据
      else if (
        detailDialogVisible.value &&
        data.pid === currentDetail.value.id
      ) {
        await getTableData();
        await refreshDetailData();
      } else {
        await getTableData();
      }
    }
  });
};

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    '<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除所选留言？</p><span style="font-size: 14px;color: #FF5240;">删除后留言将被移除</span></div>',
    "删除确认",
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }
  ).then(() => {
    batchDeleteCommentMessages(checkedList.value).then(() => {
      //更新节点
      handleResetPagination();
      // getTableData();
      handleGetFormManageList()
      ElMessage({
        showClose: true,
        message: "删除成功",
        type: "success",
      });
    });
  });
};

// 审核进度查看
const showAuditProgress = ref(false);
const processInstanceId = ref("");
const handleAuditProgress = async (data) => {
  processInstanceId.value = data;
  showAuditProgress.value = true;
  console.log("processInstanceId.value", processInstanceId.value);
};

// 添加详情相关的数据和方法
const detailDialogVisible = ref(false);
const currentDetail = ref({});
const dynamicFields = ref([]);
const userReplay = ref(false);
const showDetail = async (row) => {
  currentDetail.value = row;
  // console.log(currentDetail.value);
  dynamicFields.value = Object.keys(row.content.content);
  dynamicFields.value = dynamicFields.value.filter(
    (item) => item !== "comment"
  );
  if (row.isRead == false) {
    await readCommentMessages({
      commentId: row.id,
    })
    row.isRead = true
  }
  let res = await getCommentTreeByIdCommentMessages({
    commentId: row.id,
  });
  if (res.code === 20000) {
    currentDetail.value.children = res.data[0].children;
  } else {
    ElMessage.error("获取回复失败");
  }
  //判断该用户是否可以回复
  try {
    const isReplayRes = await canReplyCommentMessages({commentId: currentDetail.value.id});
    console.log("isReplayRes",isReplayRes);
    userReplay.value = true
  } catch (error) {
    console.log(error);
  }
  detailDialogVisible.value = true;
};

// 公开
const handleOpen = async (row) => {
  return new Promise((resolve) => {
    isOpeCommentMessages({
      id: row.id,
      isOpen: !row.isOpen ? 1 : 0,
    })
      .then(() => {
        ElMessage.success("状态更新成功");
        // 如果详情弹窗打开且是当前评论，重新获取详情数据
        if (detailDialogVisible.value && currentDetail.value.id === row.id) {
          refreshDetailData();
        }
        resolve(true);
      })
      .catch(() => {
        ElMessage.error("状态更新失败");
        resolve(false);
      });
  });
};

// 批量公开
const handleBatchOpen = () => {
  const data = {
    ids: checkedList.value,
    isAllChoose: isAllSearch.value,
    isOpen: 1,
  };
  batchIsOpenedCommentMessages(data).then((res) => {
    if (res.code === 20000) {
      ElMessage.success("状态更新成功");
      handleGetFormManageList();
      isAllSearch.value = false;
      isAllChooseBtn.value = false;
      checkedList.value = [];
    }
  });
};

//刷新详情数据
const refreshDetailData = async () => {
  try {
    const res = await getCommentByIdCommentMessages({ commentId: currentDetail.value.id });
    if (res.code === 20000) {
      currentDetail.value = res.data;
      
    }
    let messageRes = await getCommentTreeByIdCommentMessages({
      commentId: currentDetail.value.id,
    });
    if (messageRes.code === 20000) {
      currentDetail.value.children = messageRes.data[0].children;
    } 
  } catch (error) {
    ElMessage.error("获取评论详情失败");
  }
  // getReplayStateData()
};

onMounted(async() => {
  await handleGetFormManageList();
  await getForm();
});
onBeforeMount(async () => {
  await store.dispatch('flow/getOperator') 
})
</script>

<style scoped lang='scss'>

.ruifox-table-new tbody tr td{
  background-color: white;
}
.inside-comment {
  width: 100%;
}

.recommend-btn i {
  color: #ccc;
  font-size: 12px;
  cursor: pointer;
}

.header-top {
  display: flex;
  align-items: start;
  justify-content: space-between;
  .left-box {
    display: flex;
    justify-content: space-between;
  }
  .state {
    margin-right: 10px;
  }
  .right-num{
    display: flex;
    align-items: center;
    margin-top: 10px;
  }
  .right-num p{
    font-size: 14px;
    padding: 6.5px 11px;
    color: var(--el-input-text-color, var(--el-text-color-regular));
    border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
    box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;
    margin-left: 10px;
    cursor: pointer;
  }
  .right-num p span{
    font-size: 18px;
    color: #333;
  }
}


.table-td-top{
  width: 18px;
  min-width: 18px;
  .ding-yes{
    display: inline-block;
    width: 16px;
    height: 16px;
    font-size: 12px;
    color: $white;
    line-height: 16px;
    text-align: center;
    background-color: #FF5240;
    cursor: pointer;
    margin-right: 5px;
  }
  .ding-yes:hover{
    background-color: #f78a7e;
  }
  .ding-no{
    display: inline-block;
    cursor: pointer;
    width: 16px;
    height: 16px;
    font-size: 12px;
    color: $white;
    line-height: 16px;
    text-align: center;
    background-color: #D7D7D7;
    margin-right: 5px;
    visibility: hidden;
  }
  .ding-no:hover{
    background-color: #817f7f;
  }
}
.content-container{
  position: relative;
  padding-left: 5px;
  box-sizing: border-box;
  .is-read{
    position: absolute;
    left: -5px;
    top: 0;
    width: 7px;
    height: 7px;
    border-radius: 50%;
    background: #f78a7e;
  }
}

.recommend-btn.is-recommended i {
  color: $mainColor;
}
::v-deep .field-title{
    font-size: 16px;
    color: var(--el-text-color-regular);
    &.is-disabled .el-input__inner{
      -webkit-text-fill-color:#666;
    }
  }
.content-text {
  cursor: pointer;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; 
  white-space: normal; 
  font-size: 12px !important;
  max-height: 36px;
  &:hover {
    color: $mainColor;
  }
}
.content-text ::v-deep * {
  font-size: 12px !important;
  background: none !important;
}
:deep(.comment-detail-dialog) {
  .el-dialog__body {
    padding: 0; // 移除默认内边距

    .el-scrollbar {
      padding: 20px; // 将内边距添加到滚动区域
    }
  }
}

.comment-detail {
  .comment-header {
    margin-bottom: 16px;

    .header-title {
      font-size: 18px;
      font-weight: 500;
      color: #303133;
    }
  }

  .main-comment {
    padding: 16px;
    margin-bottom: 20px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;

    .comment-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .left {
        display: flex;
        align-items: center;

        .label {
          color: #606266;
          margin-right: 8px;
        }

        .value {
          color: #303133;
        }
      }

      .right {
        display: flex;
        align-items: center;
        gap: 16px;
        button{
          font-size: 14px;
        }
      }
    }

    .comment-info {
      margin: 12px 0;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      .info-item {
        width: 48%;
        display: flex;
        align-items: center;
        margin-bottom: 8px;

        &:last-child {
          margin-bottom: 0;
          width: 100%;
        }

        .label {
          color: #606266;
          margin-right: 8px;
          min-width: 70px;
        }

        .value {
          color: #303133;
        }
      }
    }

    .comment-content {
      padding: 12px 0;

      :deep(*) {
        font-size: 14px !important;
        line-height: 1.6;
      }

      :deep(img) {
        max-width: 100%;
        height: auto;
      }
    }
  }

  .reply-list {
    .reply-header {
      margin-bottom: 16px;

      .header-title {
        font-size: 18px;
        font-weight: 500;
        color: #303133;

        .count {
          font-size: 14px;
          color: #909399;
          margin-left: 4px;
          font-weight: normal;
        }
      }
    }

    .reply-items {
      .reply-item {
        padding: 16px;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        margin-bottom: 12px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
        background: #fff;
        transition: box-shadow 0.3s ease;

        &:hover {
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.04);
        }

        &:last-child {
          margin-bottom: 5px;
        }

        .reply-info {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;

          .left {
            display: flex;
            align-items: center;
            gap: 24px;

            .username {
              color: #303133;
              font-size: 14px;
            }

            .time {
              color: #909399;
              font-size: 14px;
            }
          }
          .right{
            button{
              font-size: 14px;
              margin-left: 15px;
            }
          }
        }

        .el-divider {
          margin: 12px 0;
          border-top: 1px solid #f0f0f0;
        }

        .reply-content {
          :deep(*) {
            font-size: 14px !important;
            line-height: 1.6;
          }

          :deep(img) {
            max-width: 100%;
            height: auto;
          }
        }
        .audit-progress{
            margin-top: 10px;
            .audit-title{
              font-size: 16px;
              color: #333;
            }
            .audit-list{
              display: flex;
              margin-top: 10px;
              .audit-item{
                flex: 1;
                position: relative;
                &::after{
                    position: absolute;
                    left: 0;
                    top: 10px;
                    z-index: 1;
                    content: '';
                    height: 1px;
                    width: 100%;
                    background: #dddddd;
                  }
                  &:last-child{
                    &::after{
                      display: none;
                    }
                  }
                i{
                  font-size: 20px;
                  position: relative;
                  z-index: 3;
                }
                p{
                  margin-top: 5px;
                  &.username{
                    display: flex;
                    align-items: center;
                    i{
                      margin-left: 10px;
                      font-size: 18px;
                    }
                  }
                }
              }
            }
        }
      }
    }
  }
}
.el-radio{
  margin-right: 30px;
}
</style>